/**
 * 智能医疗监测系统 - 现代化前端应用
 * 采用苹果设计理念的用户界面
 */

class MedicalMonitoringApp {
    constructor() {
        this.ws = null;
        this.charts = {};
        this.data = {
            heart: { values: [], labels: [] },
            temperature: { values: [], labels: [] },
            dropRate: { values: [], labels: [] },
            spo2: { values: [], labels: [] }
        };
        this.maxDataPoints = 30;
        this.currentPage = 1;
        this.pageSize = 20;
        this.totalRecords = 0;
        this.currentQueryData = [];
        this.chatHistory = [];

        this.init();
    }

    init() {
        this.initElements();
        this.initEventListeners();
        this.initCharts();
        this.showLoadingScreen();
        this.initNavigation();

        // 隐藏加载屏幕
        setTimeout(() => {
            this.hideLoadingScreen();
        }, 2000);
    }

    initElements() {
        // 连接相关元素
        this.elements = {
            serverUrl: document.getElementById('serverUrl'),
            connectBtn: document.getElementById('connectBtn'),
            disconnectBtn: document.getElementById('disconnectBtn'),
            connectionStatus: document.getElementById('connectionStatus'),

            // 实时数据显示
            currentHeartRate: document.getElementById('currentHeartRate'),
            currentTemperature: document.getElementById('currentTemperature'),
            currentDropRate: document.getElementById('currentDropRate'),
            currentSpo2: document.getElementById('currentSpo2'),

            // 图表画布
            heartRateChart: document.getElementById('heartRateChart'),
            temperatureChart: document.getElementById('temperatureChart'),
            dropRateChart: document.getElementById('dropRateChart'),
            spo2Chart: document.getElementById('spo2Chart'),

            // 通讯日志
            messageArea: document.getElementById('messageArea'),
            messageInput: document.getElementById('messageInput'),
            sendBtn: document.getElementById('sendBtn'),

            // AI对话
            aiMessages: document.getElementById('aiMessages'),
            aiMessageInput: document.getElementById('aiMessageInput'),
            aiSendBtn: document.getElementById('aiSendBtn'),

            // 数据管理
            startTime: document.getElementById('startTime'),
            endTime: document.getElementById('endTime'),
            heartCheck: document.getElementById('heartCheck'),
            temperatureCheck: document.getElementById('temperatureCheck'),
            dropRateCheck: document.getElementById('dropRateCheck'),
            spo2Check: document.getElementById('spo2Check'),
            queryDataBtn: document.getElementById('queryDataBtn'),
            exportPdfBtn: document.getElementById('exportPdfBtn'),
            clearDataBtn: document.getElementById('clearDataBtn'),
            refreshDataBtn: document.getElementById('refreshDataBtn'),

            // 数据显示
            totalRecords: document.getElementById('totalRecords'),
            timeRange: document.getElementById('timeRange'),
            dataTypes: document.getElementById('dataTypes'),
            dataTableBody: document.getElementById('dataTableBody'),
            currentPage: document.getElementById('currentPage'),
            totalPages: document.getElementById('totalPages'),
            prevPageBtn: document.getElementById('prevPageBtn'),
            nextPageBtn: document.getElementById('nextPageBtn'),
            pageSizeSelect: document.getElementById('pageSizeSelect'),

            // 导航
            navItems: document.querySelectorAll('.nav-item'),
            viewSections: document.querySelectorAll('.view-section'),
            pageTitle: document.getElementById('pageTitle'),
            currentBreadcrumb: document.getElementById('currentBreadcrumb'),

            // 加载屏幕
            loadingScreen: document.getElementById('loadingScreen'),

            // 通知系统
            notificationToast: document.getElementById('notificationToast'),
            confirmDialog: document.getElementById('confirmDialog'),
            confirmMessage: document.getElementById('confirmMessage'),
            confirmOk: document.getElementById('confirmOk'),
            confirmCancel: document.getElementById('confirmCancel')
        };
    }

    initEventListeners() {
        // 连接控制
        this.elements.connectBtn?.addEventListener('click', () => this.connect());
        this.elements.disconnectBtn?.addEventListener('click', () => this.disconnect());

        // 消息发送
        this.elements.sendBtn?.addEventListener('click', () => this.sendMessage());
        this.elements.messageInput?.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') this.sendMessage();
        });

        // AI对话
        this.elements.aiSendBtn?.addEventListener('click', () => this.sendAIMessage());
        this.elements.aiMessageInput?.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') this.sendAIMessage();
        });

        // 快速问题按钮
        document.querySelectorAll('.quick-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                this.elements.aiMessageInput.value = e.target.textContent;
                this.sendAIMessage();
            });
        });

        // 数据管理
        this.elements.queryDataBtn?.addEventListener('click', () => this.queryData());
        this.elements.exportPdfBtn?.addEventListener('click', () => this.exportPDF());
        this.elements.clearDataBtn?.addEventListener('click', () => this.clearData());
        this.elements.refreshDataBtn?.addEventListener('click', () => this.refreshData());

        // 分页控制
        this.elements.prevPageBtn?.addEventListener('click', () => this.previousPage());
        this.elements.nextPageBtn?.addEventListener('click', () => this.nextPage());

        // 添加测试数据按钮（用于演示）
        this.addTestDataButton();
        this.elements.pageSizeSelect?.addEventListener('change', () => this.changePageSize());

        // 快速时间选择
        document.querySelectorAll('.quick-time-btn').forEach(btn => {
            btn.addEventListener('click', (e) => this.setQuickTimeRange(e.target.dataset.hours));
        });

        // 通知关闭
        document.querySelector('.toast-close')?.addEventListener('click', () => this.hideNotification());

        // 确认对话框
        this.elements.confirmOk?.addEventListener('click', () => this.confirmAction());
        this.elements.confirmCancel?.addEventListener('click', () => this.hideConfirmDialog());
    }

    initNavigation() {
        this.elements.navItems.forEach(item => {
            item.addEventListener('click', (e) => {
                const viewName = e.currentTarget.dataset.view;
                this.switchView(viewName);
            });
        });
    }

    switchView(viewName) {
        // 更新导航状态
        this.elements.navItems.forEach(item => {
            item.classList.remove('active');
            if (item.dataset.view === viewName) {
                item.classList.add('active');
            }
        });

        // 更新视图显示
        this.elements.viewSections.forEach(section => {
            section.classList.remove('active');
        });

        const targetView = document.getElementById(`${viewName}View`);
        if (targetView) {
            targetView.classList.add('active');
        }

        // 更新页面标题
        const titles = {
            dashboard: '实时监测',
            ai: 'AI助手',
            data: '数据管理',
            settings: '系统设置'
        };

        if (this.elements.pageTitle) {
            this.elements.pageTitle.textContent = titles[viewName] || '智能医疗监测';
        }
        if (this.elements.currentBreadcrumb) {
            this.elements.currentBreadcrumb.textContent = titles[viewName] || '智能医疗监测';
        }
    }

    showLoadingScreen() {
        if (this.elements.loadingScreen) {
            this.elements.loadingScreen.classList.remove('hidden');
        }
    }

    hideLoadingScreen() {
        if (this.elements.loadingScreen) {
            this.elements.loadingScreen.classList.add('hidden');
        }
    }

    initCharts() {
        const chartConfigs = {
            heartRateChart: {
                label: '心率 (BPM)',
                borderColor: '#FF3B30',
                backgroundColor: 'rgba(255, 59, 48, 0.1)',
                yMin: 40,
                yMax: 160,
                unit: 'BPM'
            },
            temperatureChart: {
                label: '体温 (°C)',
                borderColor: '#FF9500',
                backgroundColor: 'rgba(255, 149, 0, 0.1)',
                yMin: 35,
                yMax: 42,
                unit: '°C'
            },
            dropRateChart: {
                label: '滴速 (滴/分钟)',
                borderColor: '#007AFF',
                backgroundColor: 'rgba(0, 122, 255, 0.1)',
                yMin: 0,
                yMax: 100,
                unit: '滴/分钟'
            },
            spo2Chart: {
                label: '血氧 (%)',
                borderColor: '#34C759',
                backgroundColor: 'rgba(52, 199, 89, 0.1)',
                yMin: 85,
                yMax: 100,
                unit: '%'
            }
        };

        Object.keys(chartConfigs).forEach(chartId => {
            const canvas = this.elements[chartId];
            if (canvas) {
                const config = chartConfigs[chartId];
                this.charts[chartId] = this.createChart(canvas, config);
            }
        });
    }

    createChart(canvas, config) {
        const ctx = canvas.getContext('2d');
        return new Chart(ctx, {
            type: 'line',
            data: {
                labels: [],
                datasets: [{
                    label: config.label,
                    data: [],
                    borderColor: config.borderColor,
                    backgroundColor: config.backgroundColor,
                    tension: 0.4,
                    fill: true,
                    pointRadius: 3,
                    pointHoverRadius: 6,
                    borderWidth: 2
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                interaction: {
                    intersect: false,
                    mode: 'index'
                },
                scales: {
                    y: {
                        beginAtZero: false,
                        suggestedMin: config.yMin,
                        suggestedMax: config.yMax,
                        grid: {
                            color: 'rgba(0, 0, 0, 0.05)'
                        },
                        ticks: {
                            color: '#6B7280'
                        }
                    },
                    x: {
                        grid: {
                            color: 'rgba(0, 0, 0, 0.05)'
                        },
                        ticks: {
                            color: '#6B7280',
                            maxTicksLimit: 8
                        }
                    }
                },
                plugins: {
                    legend: {
                        display: false
                    },
                    tooltip: {
                        backgroundColor: 'rgba(0, 0, 0, 0.8)',
                        titleColor: 'white',
                        bodyColor: 'white',
                        borderColor: config.borderColor,
                        borderWidth: 1,
                        cornerRadius: 8,
                        displayColors: false
                    }
                },
                animation: {
                    duration: 300,
                    easing: 'easeOutQuart'
                }
            }
        });
    }

    // 连接管理
    connect() {
        if (this.ws) {
            this.showNotification('已连接', 'warning');
            return;
        }

        const url = this.elements.serverUrl?.value;
        if (!url) {
            this.showNotification('请输入服务器地址', 'error');
            return;
        }

        this.updateConnectionStatus('连接中...', false);
        this.ws = new WebSocket(url);

        this.ws.onopen = () => {
            this.log('连接成功');
            this.updateConnectionStatus('已连接', true);
            this.updateConnectionButtons(true);
        };

        this.ws.onmessage = (e) => {
            const msg = String(e.data);
            this.log(`收到: ${msg}`);
            this.processMessage(msg);
        };

        this.ws.onerror = (e) => {
            this.log('连接错误', 'error');
            this.updateConnectionStatus('连接错误', false);
            console.error(e);
        };

        this.ws.onclose = () => {
            this.log('连接断开');
            this.updateConnectionStatus('未连接', false);
            this.updateConnectionButtons(false);
            this.ws = null;
            this.resetDisplayValues();
        };
    }

    disconnect() {
        if (this.ws) {
            this.ws.close();
        }
    }

    updateConnectionStatus(text, connected) {
        const statusDot = document.querySelector('.status-dot');
        const statusText = document.querySelector('.status-text');

        if (statusDot) {
            statusDot.classList.toggle('connected', connected);
        }
        if (statusText) {
            statusText.textContent = text;
        }
    }

    updateConnectionButtons(connected) {
        if (this.elements.connectBtn) {
            this.elements.connectBtn.disabled = connected;
        }
        if (this.elements.disconnectBtn) {
            this.elements.disconnectBtn.disabled = !connected;
        }
        if (this.elements.sendBtn) {
            this.elements.sendBtn.disabled = !connected;
        }
        if (this.elements.serverUrl) {
            this.elements.serverUrl.disabled = connected;
        }
    }

    resetDisplayValues() {
        const elements = [
            'currentHeartRate',
            'currentTemperature',
            'currentDropRate',
            'currentSpo2'
        ];

        elements.forEach(id => {
            const element = this.elements[id];
            if (element) {
                element.textContent = '--';
            }
        });
    }

    processMessage(msg) {
        if (msg.startsWith("Heart:")) {
            const value = this.parseValue(msg, "Heart:");
            if (value !== null) {
                this.updateMetric('heart', value, 'currentHeartRate', 'heartRateChart');
            }
        } else if (msg.startsWith("Temperature:")) {
            const value = this.parseValue(msg, "Temperature:");
            if (value !== null) {
                this.updateMetric('temperature', value, 'currentTemperature', 'temperatureChart');
            }
        } else if (msg.startsWith("DropRate:")) {
            const value = this.parseValue(msg, "DropRate:");
            if (value !== null) {
                this.updateMetric('dropRate', value, 'currentDropRate', 'dropRateChart');
            }
        } else if (msg.startsWith("n_spo2:")) {
            const value = this.parseValue(msg, "n_spo2:");
            if (value !== null) {
                this.updateMetric('spo2', value, 'currentSpo2', 'spo2Chart');
            }
        }
    }

    parseValue(msg, prefix) {
        try {
            const valueStr = msg.substring(prefix.length).trim();
            const value = parseFloat(valueStr);
            return isNaN(value) ? null : value;
        } catch (err) {
            this.log(`解析数据错误: ${err}`, 'error');
            return null;
        }
    }

    updateMetric(dataKey, value, displayElementId, chartId) {
        // 更新显示值
        const displayElement = this.elements[displayElementId];
        if (displayElement) {
            displayElement.textContent = value;
        }

        // 更新图表
        const chart = this.charts[chartId];
        if (chart) {
            this.updateChart(chart, dataKey, value);
        }

        // 更新状态指示器
        this.updateMetricStatus(dataKey, value);

        // 保存数据到数据库
        this.saveDataToDatabase(dataKey, value);
    }

    updateChart(chart, dataKey, value) {
        const now = new Date();
        const timeLabel = now.toLocaleTimeString().split(' ')[0];

        // 添加新数据
        chart.data.labels.push(timeLabel);
        chart.data.datasets[0].data.push(value);

        // 限制数据点数量
        if (chart.data.labels.length > this.maxDataPoints) {
            chart.data.labels.shift();
            chart.data.datasets[0].data.shift();
        }

        chart.update('none');
    }

    updateMetricStatus(dataKey, value) {
        // 根据数值更新状态指示器
        const statusRanges = {
            heart: { normal: [60, 100], warning: [50, 120] },
            temperature: { normal: [36, 37.5], warning: [35, 39] },
            dropRate: { normal: [20, 60], warning: [10, 80] },
            spo2: { normal: [95, 100], warning: [90, 100] }
        };

        const range = statusRanges[dataKey];
        if (!range) return;

        let status = 'danger';
        if (value >= range.normal[0] && value <= range.normal[1]) {
            status = 'normal';
        } else if (value >= range.warning[0] && value <= range.warning[1]) {
            status = 'warning';
        }

        // 更新对应的状态徽章
        const metricCard = document.querySelector(`.metric-card.${dataKey.replace(/([A-Z])/g, '-$1').toLowerCase()}`);
        if (metricCard) {
            const statusBadge = metricCard.querySelector('.status-badge');
            if (statusBadge) {
                statusBadge.className = `status-badge ${status}`;
                statusBadge.textContent = status === 'normal' ? '正常' :
                                        status === 'warning' ? '注意' : '异常';
            }
        }
    }

    // 保存数据到数据库
    async saveDataToDatabase(dataKey, value) {
        try {
            // 将dataKey转换为后端期望的数据类型
            const dataTypeMap = {
                'heart': 'Heart',
                'temperature': 'Temperature',
                'dropRate': 'DropRate',
                'spo2': 'n_spo2'
            };

            const dataType = dataTypeMap[dataKey];
            if (!dataType) {
                console.error('未知的数据类型:', dataKey);
                return;
            }

            const payload = {
                dataType: dataType,
                value: value,
                timestamp: Date.now(),
                deviceId: 'web-client'
            };

            console.log('保存数据到数据库:', payload); // 调试日志

            const response = await fetch('/api/data/save', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(payload)
            });

            const result = await response.json();
            if (result.success) {
                console.log('数据保存成功:', dataType, value); // 调试日志
            } else {
                console.error('数据保存失败:', result.error);
            }

        } catch (error) {
            console.error('保存数据时发生错误:', error);
        }
    }

    addMessage(content, isUser) {
        const msgDiv = document.createElement('div');
        msgDiv.className = `message ${isUser ? 'user-message' : 'ai-message'}`;

        // 创建消息结构
        const messageAvatar = document.createElement('div');
        messageAvatar.className = 'message-avatar';
        messageAvatar.innerHTML = isUser ? '<i class="fas fa-user"></i>' : '<i class="fas fa-robot"></i>';

        const messageContent = document.createElement('div');
        messageContent.className = 'message-content';

        const messageText = document.createElement('div');
        messageText.className = 'message-text';
        messageText.textContent = content;

        const messageTime = document.createElement('div');
        messageTime.className = 'message-time';
        messageTime.textContent = new Date().toLocaleTimeString();

        messageContent.appendChild(messageText);
        messageContent.appendChild(messageTime);

        msgDiv.appendChild(messageAvatar);
        msgDiv.appendChild(messageContent);

        if (this.elements.aiMessages) {
            this.elements.aiMessages.appendChild(msgDiv);
            this.elements.aiMessages.scrollTop = this.elements.aiMessages.scrollHeight;
        }

        // 更新聊天历史
        this.chatHistory.push({
            role: isUser ? 'user' : 'assistant',
            content: content
        });

        // 保持历史记录在合理范围内
        if (this.chatHistory.length > 10) {
            this.chatHistory = this.chatHistory.slice(this.chatHistory.length - 10);
        }
    }

    showThinking() {
        const thinkingDiv = document.createElement('div');
        thinkingDiv.className = 'message ai-message';
        thinkingDiv.innerHTML = `
            <div class="message-avatar">
                <i class="fas fa-robot"></i>
            </div>
            <div class="message-content">
                <div class="message-text">
                    <i class="fas fa-spinner fa-spin"></i> AI思考中...
                </div>
            </div>
        `;
        thinkingDiv.id = 'ai-thinking-indicator';

        if (this.elements.aiMessages) {
            this.elements.aiMessages.appendChild(thinkingDiv);
            this.elements.aiMessages.scrollTop = this.elements.aiMessages.scrollHeight;
        }
        return thinkingDiv;
    }

    removeThinking(element) {
        if (element && element.parentNode) {
            element.parentNode.removeChild(element);
        }
    }

    async callAIAPI(message) {
        try {
            const thinking = this.showThinking();

            // 获取用户的医疗数据上下文
            const medicalContext = await this.getMedicalDataContext();
            console.log('医疗数据上下文:', medicalContext); // 调试日志

            // 构建系统提示，包含医疗数据上下文
            const systemPrompt = this.buildSystemPrompt(medicalContext);
            console.log('系统提示长度:', systemPrompt.length); // 调试日志

            // 构建消息历史，符合OpenAI格式
            const messages = [
                {
                    role: 'system',
                    content: systemPrompt
                },
                // 添加历史对话
                ...this.chatHistory,
                // 添加当前消息
                {
                    role: 'user',
                    content: message
                }
            ];

            // 发送请求到后端，后端调用AI API
            const response = await fetch('/api/ai/chat', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    messages: messages
                })
            });

            if (!response.ok) {
                throw new Error(`HTTP ${response.status}: ${response.statusText}`);
            }

            const data = await response.json();
            this.removeThinking(thinking);

            if (data.error) {
                this.log(`AI调用错误: ${data.error}`, 'error');
                this.addMessage(`抱歉，发生了错误: ${data.error}`, false);
            } else if (data.content) {
                this.addMessage(data.content, false);
            } else {
                this.addMessage('抱歉，AI没有返回有效回复', false);
            }

        } catch (error) {
            console.error('AI API调用失败:', error);
            this.log(`AI API调用失败: ${error.message}`, 'error');
            this.removeThinking(document.getElementById('ai-thinking-indicator'));
            this.addMessage(`抱歉，AI服务暂时不可用: ${error.message}`, false);
        }
    }

    sendAIMessage() {
        const msg = this.elements.aiMessageInput?.value.trim();
        if (!msg) {
            this.showNotification('AI提问不能为空', 'warning');
            return;
        }

        this.addMessage(msg, true);
        if (this.elements.aiMessageInput) {
            this.elements.aiMessageInput.value = '';
        }
        this.callAIAPI(msg);
    }

    // 获取医疗数据上下文
    async getMedicalDataContext() {
        try {
            // 获取最近24小时的数据作为上下文
            const endTime = Date.now();
            const startTime = endTime - (24 * 60 * 60 * 1000); // 24小时前

            const params = new URLSearchParams({
                startTime: startTime,
                endTime: endTime,
                dataTypes: 'Heart,DropRate,Temperature,n_spo2',
                limit: 50, // 获取最近50条记录
                offset: 0
            });

            console.log('查询医疗数据参数:', params.toString()); // 调试日志
            const response = await fetch(`/api/data/query?${params}`);
            const result = await response.json();
            console.log('医疗数据查询结果:', result); // 调试日志

            if (result.success && result.data) {
                console.log('找到医疗数据:', result.data.length, '条记录'); // 调试日志
                return this.analyzeDataForContext(result.data);
            }
            console.log('没有找到医疗数据或查询失败'); // 调试日志
            return null;
        } catch (error) {
            console.error('获取医疗数据上下文失败:', error);
            return null;
        }
    }

    // 分析数据生成上下文摘要
    analyzeDataForContext(data) {
        console.log('开始分析医疗数据:', data); // 调试日志

        if (!data || data.length === 0) {
            console.log('没有数据可分析'); // 调试日志
            return {
                summary: '暂无医疗数据记录',
                hasData: false
            };
        }

        // 按数据类型分组
        const groupedData = {
            Heart: [],
            DropRate: [],
            Temperature: [],
            n_spo2: []
        };

        data.forEach(record => {
            if (groupedData[record.data_type]) {
                groupedData[record.data_type].push(record.value);
            }
        });

        // 计算统计信息
        const stats = {};
        Object.keys(groupedData).forEach(type => {
            const values = groupedData[type];
            if (values.length > 0) {
                stats[type] = {
                    count: values.length,
                    latest: values[values.length - 1],
                    average: (values.reduce((a, b) => a + b, 0) / values.length).toFixed(1),
                    min: Math.min(...values),
                    max: Math.max(...values)
                };
            }
        });

        // 生成数据摘要
        const summary = this.generateDataSummary(stats, data);

        return {
            summary,
            stats,
            recordCount: data.length,
            timeRange: {
                start: new Date(Math.min(...data.map(d => d.timestamp))).toLocaleString(),
                end: new Date(Math.max(...data.map(d => d.timestamp))).toLocaleString()
            },
            hasData: true
        };
    }

    // 生成数据摘要文本
    generateDataSummary(stats, data) {
        const summaryParts = [];

        summaryParts.push(`用户最近24小时内共有${data.length}条医疗数据记录。`);

        if (stats.Heart) {
            const heartStatus = this.getHeartRateStatus(stats.Heart.latest);
            summaryParts.push(`心率：最新值${stats.Heart.latest}BPM，平均${stats.Heart.average}BPM，范围${stats.Heart.min}-${stats.Heart.max}BPM（${heartStatus}）。`);
        }

        if (stats.Temperature) {
            const tempStatus = this.getTemperatureStatus(stats.Temperature.latest);
            summaryParts.push(`体温：最新值${stats.Temperature.latest}°C，平均${stats.Temperature.average}°C，范围${stats.Temperature.min}-${stats.Temperature.max}°C（${tempStatus}）。`);
        }

        if (stats.n_spo2) {
            const spo2Status = this.getSpo2Status(stats.n_spo2.latest);
            summaryParts.push(`血氧：最新值${stats.n_spo2.latest}%，平均${stats.n_spo2.average}%，范围${stats.n_spo2.min}-${stats.n_spo2.max}%（${spo2Status}）。`);
        }

        if (stats.DropRate) {
            summaryParts.push(`滴速：最新值${stats.DropRate.latest}滴/分钟，平均${stats.DropRate.average}滴/分钟，范围${stats.DropRate.min}-${stats.DropRate.max}滴/分钟。`);
        }

        return summaryParts.join(' ');
    }

    // 心率状态评估
    getHeartRateStatus(heartRate) {
        if (heartRate < 60) return '偏低';
        if (heartRate > 100) return '偏高';
        return '正常';
    }

    // 体温状态评估
    getTemperatureStatus(temperature) {
        if (temperature < 36.0) return '偏低';
        if (temperature > 37.5) return '偏高';
        return '正常';
    }

    // 血氧状态评估
    getSpo2Status(spo2) {
        if (spo2 < 95) return '偏低';
        return '正常';
    }

    // 构建系统提示
    buildSystemPrompt(medicalContext) {
        let systemPrompt = `你是一个专业的医疗监测系统AI助手，专门帮助用户理解和分析医疗数据。请用简洁、专业且易懂的语言回答问题。

重要提醒：
1. 你的建议仅供参考，不能替代专业医疗诊断
2. 如发现异常数据，建议用户咨询医疗专业人员
3. 基于提供的数据进行分析，给出客观、实用的健康建议

`;

        if (medicalContext && medicalContext.hasData) {
            systemPrompt += `用户当前医疗数据概况：
${medicalContext.summary}

数据时间范围：${medicalContext.timeRange.start} 至 ${medicalContext.timeRange.end}

请基于这些实际数据回答用户的问题，提供个性化的分析和建议。`;
        } else {
            systemPrompt += `当前暂无用户的医疗数据记录，请提供一般性的医疗健康建议。`;
        }

        return systemPrompt;
    }

    // 添加测试数据按钮（用于演示AI分析功能）
    addTestDataButton() {
        // 检查是否已经添加过按钮
        if (document.getElementById('generateTestDataBtn')) return;

        const aiView = document.querySelector('[data-view="ai"]');
        if (!aiView) return;

        const chatContainer = aiView.querySelector('.chat-container');
        if (!chatContainer) return;

        // 创建测试数据按钮
        const testDataDiv = document.createElement('div');
        testDataDiv.style.cssText = `
            padding: 10px;
            text-align: center;
            border-bottom: 1px solid #e0e0e0;
            background: #f8f9fa;
        `;

        testDataDiv.innerHTML = `
            <button id="generateTestDataBtn" style="
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                color: white;
                border: none;
                padding: 8px 16px;
                border-radius: 6px;
                cursor: pointer;
                font-size: 12px;
                margin-right: 10px;
            ">生成测试数据</button>
            <button id="testDataContextBtn" style="
                background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
                color: white;
                border: none;
                padding: 8px 16px;
                border-radius: 6px;
                cursor: pointer;
                font-size: 12px;
                margin-right: 10px;
            ">测试数据获取</button>
            <span style="font-size: 12px; color: #666;">
                生成一些测试医疗数据，体验AI分析功能
            </span>
        `;

        chatContainer.insertBefore(testDataDiv, chatContainer.firstChild);

        // 添加点击事件
        document.getElementById('generateTestDataBtn').addEventListener('click', () => {
            this.generateTestMedicalData();
        });

        document.getElementById('testDataContextBtn').addEventListener('click', () => {
            this.testDataContext();
        });
    }

    // 生成测试医疗数据
    async generateTestMedicalData() {
        try {
            const button = document.getElementById('generateTestDataBtn');
            button.disabled = true;
            button.textContent = '生成中...';

            // 生成最近2小时的测试数据
            const now = Date.now();
            const dataPoints = [];

            for (let i = 0; i < 20; i++) {
                const timestamp = now - (i * 6 * 60 * 1000); // 每6分钟一个数据点

                // 生成心率数据 (60-100 BPM)
                dataPoints.push({
                    dataType: 'Heart',
                    value: Math.floor(Math.random() * 40) + 60,
                    timestamp: timestamp,
                    deviceId: 'test-device'
                });

                // 生成体温数据 (36.0-37.5°C)
                dataPoints.push({
                    dataType: 'Temperature',
                    value: Math.round((Math.random() * 1.5 + 36.0) * 10) / 10,
                    timestamp: timestamp,
                    deviceId: 'test-device'
                });

                // 生成血氧数据 (95-100%)
                dataPoints.push({
                    dataType: 'n_spo2',
                    value: Math.floor(Math.random() * 5) + 95,
                    timestamp: timestamp,
                    deviceId: 'test-device'
                });

                // 生成滴速数据 (20-60 滴/分钟)
                dataPoints.push({
                    dataType: 'DropRate',
                    value: Math.floor(Math.random() * 40) + 20,
                    timestamp: timestamp,
                    deviceId: 'test-device'
                });
            }

            // 批量保存数据
            for (const dataPoint of dataPoints) {
                await fetch('/api/data/save', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(dataPoint)
                });
            }

            this.showNotification('测试数据生成成功！现在可以询问AI关于您的数据了', 'success');

            // 添加提示消息
            this.addMessage('我已经为您生成了一些测试医疗数据。现在您可以问我关于您的心率、体温、血氧等数据的问题了！', false);

        } catch (error) {
            console.error('生成测试数据失败:', error);
            this.showNotification('生成测试数据失败', 'error');
        } finally {
            const button = document.getElementById('generateTestDataBtn');
            button.disabled = false;
            button.textContent = '生成测试数据';
        }
    }

    // 测试数据上下文获取
    async testDataContext() {
        try {
            console.log('=== 测试数据上下文获取 ===');
            const context = await this.getMedicalDataContext();
            console.log('获取到的医疗数据上下文:', context);

            if (context && context.hasData) {
                this.addMessage(`测试成功！找到了${context.recordCount}条医疗数据记录。数据摘要：${context.summary}`, false);
            } else {
                this.addMessage('测试结果：没有找到医疗数据。请先生成一些测试数据或连接设备采集数据。', false);
            }
        } catch (error) {
            console.error('测试数据上下文失败:', error);
            this.addMessage(`测试失败：${error.message}`, false);
        }
    }

    // 消息和日志系统
    log(message, type = 'info') {
        const now = new Date();
        const timestamp = now.toLocaleTimeString();
        const logMessage = `[${timestamp}] [${type.toUpperCase()}] ${message}\n`;

        if (this.elements.messageArea) {
            this.elements.messageArea.value += logMessage;
            this.elements.messageArea.scrollTop = this.elements.messageArea.scrollHeight;
        }
    }

    sendMessage() {
        if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
            this.showNotification('未连接或连接未打开', 'error');
            return;
        }

        const msg = this.elements.messageInput?.value;
        if (!msg) {
            this.showNotification('消息不能为空', 'warning');
            return;
        }

        this.ws.send(msg);
        this.log(`发送: ${msg}`);
        if (this.elements.messageInput) {
            this.elements.messageInput.value = '';
        }
    }

    // 数据管理功能
    setQuickTimeRange(hours) {
        const now = new Date();
        const startTime = new Date(now.getTime() - hours * 60 * 60 * 1000);

        if (this.elements.startTime) {
            this.elements.startTime.value = this.formatDateTimeLocal(startTime);
        }
        if (this.elements.endTime) {
            this.elements.endTime.value = this.formatDateTimeLocal(now);
        }

        // 更新按钮状态
        document.querySelectorAll('.quick-time-btn').forEach(btn => {
            btn.classList.remove('active');
            if (btn.dataset.hours === hours.toString()) {
                btn.classList.add('active');
            }
        });
    }

    formatDateTimeLocal(date) {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        return `${year}-${month}-${day}T${hours}:${minutes}`;
    }

    async queryData() {
        try {
            const startTime = this.elements.startTime?.value;
            const endTime = this.elements.endTime?.value;

            if (!startTime || !endTime) {
                this.showNotification('请选择时间范围', 'warning');
                return;
            }

            const dataTypes = [];
            if (this.elements.heartCheck?.checked) dataTypes.push('Heart');
            if (this.elements.temperatureCheck?.checked) dataTypes.push('Temperature');
            if (this.elements.dropRateCheck?.checked) dataTypes.push('DropRate');
            if (this.elements.spo2Check?.checked) dataTypes.push('n_spo2');

            if (dataTypes.length === 0) {
                this.showNotification('请至少选择一种数据类型', 'warning');
                return;
            }

            const startTimestamp = new Date(startTime).getTime();
            const endTimestamp = new Date(endTime).getTime();

            const params = new URLSearchParams({
                startTime: startTimestamp,
                endTime: endTimestamp,
                dataTypes: dataTypes.join(','),
                offset: (this.currentPage - 1) * this.pageSize,
                limit: this.pageSize
            });

            const response = await fetch(`/api/data/query?${params}`);
            const result = await response.json();

            console.log('查询结果:', result); // 调试日志

            if (result.success) {
                this.displayQueryResults(result);
                this.showNotification('数据查询成功', 'success');
            } else {
                this.showNotification(`查询失败: ${result.message}`, 'error');
            }

        } catch (error) {
            console.error('查询数据失败:', error);
            this.showNotification(`查询失败: ${error.message}`, 'error');
        }
    }

    displayQueryResults(result) {
        // 更新统计信息
        const totalCount = result.count || result.total || 0;
        console.log('显示查询结果 - 总记录数:', totalCount, '原始结果:', result); // 调试日志

        if (this.elements.totalRecords) {
            this.elements.totalRecords.textContent = totalCount;
            console.log('已更新总记录数显示:', totalCount); // 调试日志
        }
        if (this.elements.timeRange) {
            const start = new Date(parseInt(result.query?.startTime || result.startTime)).toLocaleString();
            const end = new Date(parseInt(result.query?.endTime || result.endTime)).toLocaleString();
            this.elements.timeRange.textContent = `${start} ~ ${end}`;
        }
        if (this.elements.dataTypes) {
            const dataTypes = result.query?.dataTypes || result.dataTypes || [];
            this.elements.dataTypes.textContent = dataTypes.join(', ') || '--';
        }

        // 更新表格
        this.updateDataTable(result.data || []);

        // 更新分页
        this.updatePagination(totalCount);
    }

    updateDataTable(data) {
        if (!this.elements.dataTableBody) return;

        if (data.length === 0) {
            this.elements.dataTableBody.innerHTML = `
                <tr class="no-data">
                    <td colspan="5">
                        <div class="empty-state">
                            <i class="fas fa-search"></i>
                            <p>暂无数据</p>
                            <small>请调整查询条件后重试</small>
                        </div>
                    </td>
                </tr>
            `;
            return;
        }

        const rows = data.map(record => {
            const time = new Date(record.timestamp).toLocaleString();
            const unit = this.getDataUnit(record.data_type);
            return `
                <tr>
                    <td>${time}</td>
                    <td>${this.getDataTypeLabel(record.data_type)}</td>
                    <td>${record.value}</td>
                    <td>${unit}</td>
                    <td>${record.device_id || '--'}</td>
                </tr>
            `;
        }).join('');

        this.elements.dataTableBody.innerHTML = rows;
    }

    getDataTypeLabel(type) {
        const labels = {
            'Heart': '心率',
            'Temperature': '体温',
            'DropRate': '滴速',
            'n_spo2': '血氧'
        };
        return labels[type] || type;
    }

    getDataUnit(type) {
        const units = {
            'Heart': 'BPM',
            'Temperature': '°C',
            'DropRate': '滴/分钟',
            'n_spo2': '%'
        };
        return units[type] || '';
    }

    updatePagination(total) {
        this.totalRecords = total;
        const totalPages = Math.ceil(total / this.pageSize);

        if (this.elements.currentPage) {
            this.elements.currentPage.textContent = this.currentPage;
        }
        if (this.elements.totalPages) {
            this.elements.totalPages.textContent = totalPages;
        }

        if (this.elements.prevPageBtn) {
            this.elements.prevPageBtn.disabled = this.currentPage <= 1;
        }
        if (this.elements.nextPageBtn) {
            this.elements.nextPageBtn.disabled = this.currentPage >= totalPages;
        }
    }

    previousPage() {
        if (this.currentPage > 1) {
            this.currentPage--;
            this.queryData();
        }
    }

    nextPage() {
        const totalPages = Math.ceil(this.totalRecords / this.pageSize);
        if (this.currentPage < totalPages) {
            this.currentPage++;
            this.queryData();
        }
    }

    changePageSize() {
        this.pageSize = parseInt(this.elements.pageSizeSelect?.value) || 20;
        this.currentPage = 1;
        this.queryData();
    }

    async exportPDF() {
        try {
            const startTime = this.elements.startTime?.value;
            const endTime = this.elements.endTime?.value;

            if (!startTime || !endTime) {
                this.showNotification('请选择时间范围', 'warning');
                return;
            }

            const dataTypes = [];
            if (this.elements.heartCheck?.checked) dataTypes.push('Heart');
            if (this.elements.temperatureCheck?.checked) dataTypes.push('Temperature');
            if (this.elements.dropRateCheck?.checked) dataTypes.push('DropRate');
            if (this.elements.spo2Check?.checked) dataTypes.push('n_spo2');

            if (dataTypes.length === 0) {
                this.showNotification('请至少选择一种数据类型', 'warning');
                return;
            }

            // 禁用按钮并显示加载状态
            if (this.elements.exportPdfBtn) {
                this.elements.exportPdfBtn.disabled = true;
                this.elements.exportPdfBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> <span>导出中...</span>';
            }

            const startTimestamp = new Date(startTime).getTime();
            const endTimestamp = new Date(endTime).getTime();

            const response = await fetch('/api/data/export/pdf', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    startTime: startTimestamp,
                    endTime: endTimestamp,
                    dataTypes: dataTypes
                })
            });

            if (!response.ok) {
                throw new Error(`HTTP ${response.status}: ${response.statusText}`);
            }

            // 下载PDF文件
            const blob = await response.blob();
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.style.display = 'none';
            a.href = url;
            a.download = `医疗数据报告_${new Date().toISOString().slice(0, 10)}.pdf`;
            document.body.appendChild(a);
            a.click();
            window.URL.revokeObjectURL(url);
            document.body.removeChild(a);

            this.showNotification('PDF报告导出成功', 'success');

        } catch (error) {
            console.error('PDF导出失败:', error);
            this.showNotification(`PDF导出失败: ${error.message}`, 'error');
        } finally {
            // 恢复按钮状态
            if (this.elements.exportPdfBtn) {
                this.elements.exportPdfBtn.disabled = false;
                this.elements.exportPdfBtn.innerHTML = '<i class="fas fa-file-pdf"></i> <span>导出PDF</span>';
            }
        }
    }

    async clearData() {
        const confirmed = await this.showConfirmDialog('确定要清空所有数据吗？此操作不可撤销。');
        if (!confirmed) {
            console.log('用户取消了清空操作'); // 调试日志
            return;
        }

        console.log('开始清空数据...'); // 调试日志

        try {
            // 为了清空所有数据，我们提供所有数据类型作为筛选条件
            const response = await fetch('/api/data/clear', {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    confirmDelete: true,
                    dataTypes: ['Heart', 'DropRate', 'Temperature', 'n_spo2'] // 包含所有数据类型
                })
            });

            const result = await response.json();
            console.log('清空数据API响应:', result); // 调试日志

            if (result.success) {
                this.showNotification(`数据清空成功，删除了${result.deletedCount || 0}条记录`, 'success');
                this.queryData(); // 刷新显示
            } else {
                console.error('清空失败:', result); // 调试日志
                this.showNotification(`清空失败: ${result.error || result.message}`, 'error');
            }

        } catch (error) {
            console.error('清空数据失败:', error);
            this.showNotification(`清空失败: ${error.message}`, 'error');
        }
    }

    refreshData() {
        this.queryData();
    }

    // 通知系统
    showNotification(message, type = 'info') {
        const toast = this.elements.notificationToast;
        if (!toast) return;

        const toastIcon = toast.querySelector('.toast-icon i');
        const toastTitle = toast.querySelector('.toast-title');
        const toastText = toast.querySelector('.toast-text');

        // 设置图标和颜色
        const config = {
            success: { icon: 'fas fa-check-circle', color: '#34C759', title: '成功' },
            error: { icon: 'fas fa-exclamation-circle', color: '#FF3B30', title: '错误' },
            warning: { icon: 'fas fa-exclamation-triangle', color: '#FF9500', title: '警告' },
            info: { icon: 'fas fa-info-circle', color: '#007AFF', title: '信息' }
        };

        const typeConfig = config[type] || config.info;

        if (toastIcon) {
            toastIcon.className = typeConfig.icon;
            toastIcon.parentElement.style.backgroundColor = typeConfig.color;
        }
        if (toastTitle) {
            toastTitle.textContent = typeConfig.title;
        }
        if (toastText) {
            toastText.textContent = message;
        }

        // 显示通知
        toast.classList.add('show');

        // 自动隐藏
        setTimeout(() => {
            this.hideNotification();
        }, 5000);
    }

    hideNotification() {
        if (this.elements.notificationToast) {
            this.elements.notificationToast.classList.remove('show');
        }
    }

    showConfirmDialog(message) {
        return new Promise((resolve) => {
            const dialog = this.elements.confirmDialog;
            const messageEl = this.elements.confirmMessage;

            if (messageEl) {
                messageEl.textContent = message;
            }

            if (dialog) {
                dialog.classList.add('show');
            }

            this.confirmResolve = resolve;
        });
    }

    hideConfirmDialog() {
        if (this.elements.confirmDialog) {
            this.elements.confirmDialog.classList.remove('show');
        }
        if (this.confirmResolve) {
            this.confirmResolve(false);
            this.confirmResolve = null;
        }
    }

    confirmAction() {
        if (this.elements.confirmDialog) {
            this.elements.confirmDialog.classList.remove('show');
        }
        if (this.confirmResolve) {
            this.confirmResolve(true);
            this.confirmResolve = null;
        }
    }
}

// 初始化应用
document.addEventListener('DOMContentLoaded', () => {
    window.medicalApp = new MedicalMonitoringApp();
});